var hsList = [];

function initPage() {
    jQuery("img#logo_preview").hide();
    jQuery("img.exportlogo").hide();
    jQuery("img.importlogo").hide();
    jQuery("img[logoid]").each(function(ndx, item) {
        if (jQuery(item).attr("logoid") && jQuery(item).attr("logoid") != "0") {
            item.src = generateServiceUrl({
                service : "getlogo",
                page : "companyprofile",
                params : {
                    fileid : jQuery(item).attr("logoid")
                }
            });
            jQuery(item).show();
        }
    });

    callService("companyprofile", "gethslist", {}, {
        success : function(data) {
            hsList = data;
            jQuery(".hsdropdown").each(function(ndx, item) {
                jQuery(item).append(jQuery("<option>")
                    .text("Select HS4 code")
                    .val("-")
                );
                for (var i = 0; i < data.length; i++) {
                    jQuery(item).append(jQuery("<option>")
                        .text(data[i].hscode)
                        .val(data[i].hscode)
                    );
                }
                var hscode = jQuery(item).attr("hscode");
                if (hscode) {
                    jQuery(item).val(hscode);
                }
            });
        }
    });
}

function checkboxChanged(checkboxItem) {
    var state = checkboxItem.checked;

    if (checkboxItem.name == "export") {
        if (state) {
            reveal("dt_export");
        } else {
            hide("dt_export");
        }
    } else if (checkboxItem.name == "import") {
        if (state) {
            reveal("dt_import");
        } else {
            hide("dt_import");
        }
    }
}

function uploadSponsorLogo(title, popupId, req_width, req_height, req_minwidth, req_minheight) {
    openPopup("logoupload", {
        width : 450,
        height: 180,
        title : title,
        extraParams : {
            popup_id : popupId,
            chk_width : req_width,
            chk_height : req_height,
            chk_minwidth : req_minwidth,
            chk_minheight : req_minheight
        }
    });
}

function uploadBusinessLeadPhoto(title, popupId, req_width, req_height, req_minwidth, req_minheight) {
    openPopup("logoupload", {
        width : 450,
        height: 180,
        title : title,
        extraParams : {
            popup_id : popupId,
            needThumbnail : true
        }
    });
}

function uploadCompanyLogo() {
    openPopup("logoupload", {
        width : 450,
        height: 180,
        title : "Upload your company logo",
        extraParams : {
            needThumbnail : true,
            popup_id : "company_logo"
        }
    });
}

function uploadCompanyBanner() {
    openPopup("logoupload", {
        width : 450,
        height: 180,
        title : "Upload your banner",
        extraParams : {
            popup_id : "company_logo"
        }
    });
}

function uploadExportLogo(index) {
    openPopup("logoupload", {
        width : 450,
        height: 180,
        title : "Upload your export logo",
        extraParams : {
            popup_id : "export_logo_" + index,
            chk_width : 105,
            chk_height : 105
        }
    });
}

function uploadImportLogo(index) {
    openPopup("logoupload", {
        width : 450,
        height: 180,
        title : "Upload your import logo",
        extraParams : {
            popup_id : "import_logo_" + index
        }
    });
}

function doAfterUpload(parameters) {
    if (parameters.popupId == "company_logo") {
        jQuery("input[name='logo_id']").val(popupResult.logofileid);
        jQuery("img#logo_preview")
            .attr("src", generateServiceUrl({
                service : "getlogo",
                page : "companyprofile",
                params : {
                    fileid : popupResult.logofileid
                }
            }))
            .show("fade", { }, 500)
        ;
    } else if (parameters.popupId.indexOf("export_logo") === 0) {
        var ndx = parameters.popupId.split("_")[2];
        jQuery("input[name='export_logo_id_" + ndx + "']").val(popupResult.logofileid);
        jQuery("img#export_logo_preview_" + ndx)
            .attr("src", generateServiceUrl({
                service : "getlogo",
                page : "companyprofile",
                params : {
                    fileid : popupResult.logofileid
                }
            }))
            .show("fade", { }, 500)
        ;
    } else if (parameters.popupId.indexOf("import_logo") === 0) {
        var ndx = parameters.popupId.split("_")[2];
            jQuery("input[name='import_logo_id_" + ndx + "']").val(popupResult.logofileid);
        jQuery("img#import_logo_preview_" + ndx)
            .attr("src", generateServiceUrl({
                service : "getlogo",
                page : "companyprofile",
                params : {
                    fileid : popupResult.logofileid
                }
            }))
            .show("fade", { }, 500)
        ;
    } else {
        if (typeof window[parameters.popupId + "_change"] == "function") {
            fileuploader_uploaded(parameters, popupResult, window[parameters.popupId + "_change"]);
        } else {
            fileuploader_uploaded(parameters, popupResult);
        }
    }
}

function displayError(params) {
    alert(params.txt);
}

function applyDiscountRules(profileType, sponsorType, monthCount, other) {
    var today = new Date();
    var discount = 0;
    if (profileType == "1") {
        if (sponsorType == "logo_ad" && other.linkPlace && today.getFullYear() == 2012 && today.getMonth() <= 9) {
            discount += 6000 * (9-today.getMonth() + 1);
        }
    } else if (profileType == "2") {
    } else if (profileType == "3") {
    } else if (profileType == "5") {
    }
    return discount;
}

function recalculateAmount() {
    var allowers = {};
    var months = {};
    var extras = {};
    jQuery("input[type='checkbox'].row_allower").each(function(ndx, item) {
        if (item.name.indexOf("[") < 0) {
            if (item.name != "photo") { // business lead hack
                allowers[item.name] = item.checked ? "on" : "off";
            }
        } else {
            var ndx = parseInt(item.name.split("[")[1].replace(/\]/g, ""), 10);
            var name = item.name.split("[")[0];
            if (!allowers[name]) {
                allowers[name] = [];
            }
            while (allowers[name].length < ndx) {
                allowers[name].push("");
            }
            allowers[name].push(item.checked ? "on" : "off");
        }
    });
    if (photoCount !== undefined) {
        extras.photoCount = photoCount;
    }
    jQuery("input[type='checkbox'].cell_allower").each(function(ndx, item) {
        if (item.name.indexOf("[") < 0) {
            allowers[item.name] = item.checked ? "on" : "off";
        } else {
            var name = item.name.split("[")[0];
            var ndx = parseInt(item.name.split("[")[1].replace(/\]/g, ""), 10);
            if (!allowers[name]) {
                allowers[name] = [];
            }
            while (allowers[name].length < ndx) {
                allowers[name].push("");
            }
            allowers[name].push(item.checked ? "on" : "off");
        }
    });
    jQuery("input[type='checkbox'].extra").each(function(ndx, item) {
        extras[item.name] = item.checked ? "on" : "off";
    });
    jQuery("input[type='text'].extra").each(function(ndx, item) {
        extras[item.name] = item.value;
    });
    jQuery("input[type='text'].month").each(function(ndx, item) {
        if (item.name.indexOf("[") < 0) {
            months[item.name] = item.value;
        } else {
            var ndx = parseInt(item.name.split("[")[1].replace(/\]/g, ""), 10);
            var name = item.name.split("[")[0];
            if (!months[name]) {
                months[name] = [];
            }
            while (months[name].length < ndx) {
                months[name].push(0);
            }
            months[name].push(item.value);
        }
    });
    callService("companyprofile", "calculateamount", {
        allowers : allowers,
        months : months,
        extras : extras
    }, {
        success : function(result) {
            writeAmount(result.amount);
        }
    });
}
